<template>
  <div class="online-container">
    <div class="online-tree">
      <el-input placeholder="搜索" class="search" prefix-icon="el-icon-search" clearable v-model="filterText">
      </el-input>
       <div class="onlineTree lcdp-tree">
          <el-tree  ref="tree" :data="treeData"  node-key="id"
            :default-expanded-keys="defaultExpandedKeys" @node-click="handleNodeClick" :highlight-current=true
            :filter-node-method="filterNode" v-loading="loading" :props="defaultProps">
            <span slot-scope="{ node,data }">
              <span class="treeIcon">
                <img v-if="data.fileType == 'folder'" src="../../../../assets/online-edit_img/folder.png"
                  style="width: 16px; height: 16px" />
                <img v-else src="../../../../assets/online-edit_img/file.png" style="width: 16px; height: 16px" />
              </span>
              {{ node.label }}
            </span>
          </el-tree>
       </div>
    </div>
    <div v-show="!this.display" class="prompt-infor">请先从左侧边栏选择一个文件开始编辑,然后就可以提交您的更改了</div>
    <div v-show="this.display" class="edit-container">
      <div class="top">
        <div class="button">
          <span class="edit-number">
            <span class="number">{{ getNum() }}</span>个已更改的文件
          </span>
          <button class="submit" @click="submitMsg()">创建提交</button>
        </div>
      </div>
      <div class="tabs">
        <div class="crad " :class="{ highLight: whichIndex == item.filePath, rightborder: index === cardArr.length - 1 }"
          v-for="(item, index) in cardArr" :key="item.index">
          <span class="tabContent" @click="TabPane(item, index)">{{ item.fileName }}</span> <span class="closeTab"
            @click="closeTab(item, index)">x</span>
        </div>
        <div class="clear" />
      </div>
      <jsonEditor v-show="this.display" ref="jsonEditorRef" :oldValue="oldValue" :originArray="originArray"
        @handleChangeJson="handleChangeJson" />
    </div>
    <el-dialog title="提交信息" :visible.sync="dialogMsgVisible" class="lcdp-dialog submit-dialog">
      <el-input type="textarea" style="height: 100px;margin-top: 10px" :rows="6" resize="none" placeholder="请输入提交信息"
        v-model="submitMsgContent" maxlength="100" show-word-limit>
      </el-input>
      <div slot="footer" class="dialog-footer">
        <div class="btn-box flex flex-up-down">
          <el-button class="dialog-cancel" @click="closeMsg">{{ $t('common.cancel') }}</el-button>
          <el-button class="dialog-save" type="primary" @click="submutFile()" :loading="saveLoading">提交</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { hussarAxiosRequestUtils } from 'hussar-base';
import { OlineEditApi } from '../../api/onlineEditApi/index';
import jsonEditor from '../onlineEdit/components/jsonEditor.vue';
export default {
  name: 'onlineEdit',
  components: {
    jsonEditor,
  },
  data() {
    return {
      filterText: '',
      cardArr: [],
      whichIndex: 0,
      defaultExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      token: '',
      branch: '',
      path: '',
      display: false,
      loading: false,
      treeData: [],
      oldValue: {},
      originArray: [],
      modifiedArray: [],
      dialogMsgVisible: false,
      submitMsgContent: '',
      saveLoading: false,
      isFirst: false
    }
  },
  computed: {
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.initTree();
  },
  created() {
    this.token = this.$route.query.token;
    this.branch = this.$route.query.branch;
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    TabPane(val, index) {
      this.whichIndex = val.filePath;
      this.oldValue = _.cloneDeep(val)
    },
    closeTab(val, index) {
      this.cardArr.forEach(item => {
        if (item.filePath == val.filePath) {
          this.cardArr = this.cardArr.filter(item => item.filePath !== val.filePath)
        }
      })
      if (this.cardArr.length < 1) {
        this.display = false
      } else {
        if (val.filePath == this.whichIndex) {
          this.oldValue = _.cloneDeep(this.cardArr[this.cardArr.length - 1])
          this.whichIndex = this.cardArr[this.cardArr.length - 1].filePath
        }
      }
      console.log(this.cardArr, 'this.cardArr')
    },
    submutFile() {
      const self = this;
      self.saveLoading = true;
      const ids = {
        token: this.token,
        branch: this.branch,
        fileList: this.modifiedArray,
        msg: this.submitMsgContent
      }
      hussarAxiosRequestUtils.postAction(OlineEditApi.updateFileToGitlab, ids).then(res => {
        this.$message.success(res.msg)
        self.dialogMsgVisible = false;
        self.modifiedArray = _.cloneDeep([]);
        self.originArray = _.cloneDeep([]);
        self.cardArr = _.cloneDeep([]);
        self.display = false;
        self.saveLoading = false
      }).catch(() => {
        self.saveLoading = false
      });
    },
    submitMsg() {
      const self = this;
      self.submitMsgContent = '';
      if (this.modifiedArray.length >= 1) {
        self.dialogMsgVisible = true;
      }
    },
    closeMsg() {
      const self = this;
      self.submitMsgContent = '';
      self.dialogMsgVisible = false;
    },
    initTree() {
      this.loading = true
      const ids = {
        token: this.token,
        branch: this.branch
      }
      hussarAxiosRequestUtils.postAction(OlineEditApi.getAllDirectory, ids).then(res => {
        this.treeData = res.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      });
    },
    getNum() {
      if (this.modifiedArray.length > 0) {
        return this.modifiedArray.length;
      } else {
        return 0;
      }
    },
    handleChangeJson(value) {
      const list = _.cloneDeep(value)
      this.cardArr.forEach(item => {
        if (item.filePath == value.filePath) {
          if (item.fileContent !== value.fileContent) {
            item.fileContent = _.cloneDeep(list.fileContent)
            this.whichIndex = _.cloneDeep(list.filePath)
            console.log(this.cardArr, 'cadArr')
          }
        }
      })
      if (this.modifiedArray.length >= 1) {
        let isoriginValue = false;
        let isClear = false;
        for (var i = 0; i < this.originArray.length; i++) {
          if (value.filePath == this.originArray[i].filePath) {
            if (value.fileContent !== this.originArray[i].fileContent) {
              isClear = true;
              this.modifiedArray.forEach(item => {
                if (value.filePath == item.filePath) {
                  if (value.fileContent !== item.fileContent) {
                    this.modifiedArray = this.modifiedArray.filter(item => item.filePath != value.filePath)
                    this.modifiedArray.push(list);
                  }
                  isoriginValue = true;
                }
              })
              if (isoriginValue == false) {
                this.modifiedArray.push(list);
              }
            }
          }
        }
        if (isClear == false) {
          this.modifiedArray.forEach(item => {
            if (value.filePath == item.filePath) {
              this.modifiedArray = this.modifiedArray.filter(item => item.filePath != value.filePath)
              console.log(this.modifiedArray);
              this.getNum();
            }
          })
        }
      } else {
        if (this.originArray.length >= 1) {
          this.originArray.forEach(item => {
            if (value.filePath == item.filePath && value.fileContent !== item.fileContent) {
              this.modifiedArray.push(list);
            }
          })
        }
      }
      console.log(this.modifiedArray, 'this.modifiedArray')
    },
    handleNodeClick(data) {
      if (data.fileType == 'file' && this.isFirst == false) {
        this.isFirst = true;
        this.whichIndex = _.cloneDeep(data.filePath);
        // 修改后的新数组 modifiedArray
        if (this.modifiedArray.length >= 1) {
          let isNew = false;
          let isTabs = false;
          this.modifiedArray.forEach(item => {
            if (item.filePath == data.filePath) {
              this.oldValue = _.cloneDeep(item);
              this.isFirst = false;
              this.display = true;
              isNew = true;
              this.cardArr.forEach(item => {
                if (item.filePath !== data.filePath) {
                  isTabs = true;
                }
              })
              if (isTabs == false) {
                this.cardArr.push(_.cloneDeep(item));
              }
            }
          })
          if (isNew == false && this.originArray.length >= 1) {
            let ishaveOld = false;
            this.originArray.forEach(item => {
              if (item.filePath == data.filePath) {
                this.oldValue = _.cloneDeep(item);
                this.isFirst = false;
                ishaveOld = true;
                this.display = true;
                this.cardArr.forEach(item => {
                  if (item.filePath == data.filePath) {
                    isTabs = true;
                  }
                })
                if (isTabs == false) {
                  this.cardArr.push(_.cloneDeep(item));
                }
              }
            })
            if (ishaveOld == false) {
              this.getOldValue(data);
            }
          }
        } else {
          // 调用后端接口返回的原始数据 originArray
          if (this.originArray.length >= 1) {
            let ishaveOld = false;
            let isTabs = false;
            for (var i = 0; i < this.originArray.length; i++) {
              this.originArray.forEach(item => {
                if (data.filePath == item.filePath) {
                  this.oldValue = _.cloneDeep(item);
                  this.isFirst = false;
                  ishaveOld = true;
                  this.display = true;
                  this.cardArr.forEach(item => {
                    if (item.filePath == data.filePath) {
                      isTabs = true;
                    }
                  })
                  if (isTabs == false) {
                    this.cardArr.push(_.cloneDeep(item));
                  }
                }


              })
              if (ishaveOld == false) {
                this.getOldValue(data);
              }
            }
            if (ishaveOld == false) {
              this.getOldValue(data);
            }
          } else {
            this.getOldValue(data);
          }
        }
      }
    },
    async getOldValue(data) {
      const parme = {
        token: this.token,
        branch: this.branch,
        filePath: data.filePath
      }
      await hussarAxiosRequestUtils.postAction(OlineEditApi.getFileContent, parme).then(res => {
        this.oldValue = _.cloneDeep(res.data);
        let isrepeat = false;
        if (this.originArray.length >= 1) {
          this.originArray.forEach(item => {
            if (item.filePath == data.filePath) {
              isrepeat = true;
            }
          })
          if (isrepeat == false) {
            this.originArray.push(this.oldValue)
            this.cardArr.push(_.cloneDeep(res.data));
          }
        } else {
          this.originArray.push(this.oldValue)
          this.cardArr.push(_.cloneDeep(res.data));
        }
        console.log(this.originArray, 'this.originArray')
        this.display = true;
        this.loading = false;
        this.isFirst = false;
      }).catch(() => {
        this.loading = false;
      })
    }
  },
}
</script>
<style lang="scss">


.online-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;

  .online-tree {
    height: 100%;
    padding-top: 24px;

    .onlineTree {
      height: 95%;
      padding: 20px 27px 0 40px;
      margin-left: 20px;
      overflow: auto;
    }

    width: 22%;
    background-color: #F6FBFF;
  }

  .el-tree {
    background-color: #F6FBFF !important;
  }

  .edit-container {
    width: 77%;
    height: 94%;
    padding-top: 17px;
    background-color: #fff;

  }

  .prompt-infor {
    width: 76%;
    height: 96%;
    border: 1px solid #e7e7e7;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 19px 20px 16px 0;
  }
  
.el-tree>.el-tree-node {
  min-width: 100%;
  display: inline-block;
}
.console-body .ps__rail-x.ps--clicking .ps__thumb-x, .console-body .ps__rail-x:hover>.ps__thumb-x, .console-body .ps__rail-y:focus>.ps__thumb-x{
  height: 12px !important;
}
.button {
  height: 3%;
  margin-right: 20px;
  display: flex;
  justify-content: right;

  .edit-number {
    text-align: center;
    font-size: 14px;
    font-weight: 700;
    color: #545672;
    margin: 15px 16px 0 0;

    .number {
      color: #2794F8;
      margin-right: 4px;
    }
  }

  .submit {
    width: 80px;
    height: 32px;
    display: flex;
    border: none;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
    color: #fff;
    background: #2794F8;
    border-radius: 2px;
  }
}

.code {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.CodeMirror {
  height: 100%;
}

.el-tabs {
  height: 100%;
}

.el-tabs__header {
  margin: 18px 0 2px;
}

.el-tabs__content {
  height: 100%;
}

.el-tab-pane {
  height: 100%;
  margin-top: 65px;
}

.CodeMirror-sizer {
  margin-left: 66px !important;
  padding-right: 16px !important;
  padding-bottom: 0px !important;
  margin-bottom: -16px !important;
  border-right-width: 34px !important;
}

.CodeMirror-gutters {
  left: 0 !important;
  width: 65.8px !important;
  border-right: 1px solid #ddd;
  background-color: #F8FBFE !important;
  white-space: nowrap !important;
}

.CodeMirror-linenumber {
  width: 31px !important;
}

.submit-dialog {
  width: 736px;
  margin: auto;
}

.top {
  width: 100%;
  overflow: hidden;
}

.clear {
  clear: both;
}

.tabs {
  margin-top: 24px;
}

.crad {
  width: 168px;
  height: 35px;
  float: left;
  color: #333651;
  line-height: 35px;
  cursor: pointer;
  border-radius: 2px 0 0 0;
  text-align: center;
  background-color: #fff;
  border-top: 1px solid #D5D9DC;
  border-left: 1px solid #D5D9DC;
}

.rightborder {
  border-right: 1px solid #D5D9DC;
}

.highLight {
  color: #2794F8;
}

.closeTab {
  float: right;
  color: #c0c4cc;
  cursor: pointer;
  width: 20px;
  // font-size: 12px;
  padding-right: 8px;
}

.tabContent {
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 145px;
}

.search {
  width: 82%;
  margin-left: 50px;

  .el-input__inner {
    border: none;
  }
}

.el-input__prefix {
  left: 16px;
  top: 2px;
}

.el-input--prefix .el-input__inner {
  background: #E8EFF6;
  padding: 2px 0 0 38px;
  border-radius: 18px;
}

.el-input--prefix .el-input__inner:focus {
  border: 1px solid #2794f8;
  background: #ffffff;
}

.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: #D9EDFF;
  color: #2794F8;
  border-radius: 8px;
}

.el-tree-node__content {
  height: 36px;
}

.el-tree-node__content:hover {
  background-color: #D9EDFF;
  color: #2794F8;
  border-radius: 8px;
}

.treeIcon {
  img {
    display: inline-block;
    margin-bottom: 4px;
    vertical-align: middle;
  }
}

.el-textarea__inner {
  height: 96px;
}

.lcdp-dialog .el-dialog .el-dialog__body {
  height: calc(100% - 95px)
}

.el-textarea .el-input__count {
  bottom: 10px;
}

.online-tree .search .el-input__inner {
  height: 32px;
  line-height: 32px;
}
}
</style>
